package com.ghca.myinfo3.system.service.impl;

import com.ghca.myinfo3.system.entity.Permission;
import com.ghca.myinfo3.system.entity.Role;
import com.ghca.myinfo3.system.entity.User;
import com.ghca.myinfo3.system.mapper.PermissionMapper;
import com.ghca.myinfo3.system.repository.PermissionRepository;
import com.ghca.myinfo3.system.repository.UserRepository;
import com.ghca.myinfo3.system.service.IPermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2016/12/18.
 */
@Service
public class PermissionService implements IPermissionService {

    @Resource
    private PermissionRepository permissionRepository;

    @Resource
    private UserRepository userRepository;



    @Override
    public Permission addPermission(Permission permission) {
        return addPermission(null, permission);
    }

    @Override
    public Permission addPermission(Long parentId, Permission permission) {
        Permission parent = null;
        if (parentId != null) {
            parent = permissionRepository.findOne(parentId);
        }
        permission.setParent(parent);
        return permissionRepository.save(permission);
    }

    @Override
    public List<Permission> findRoot() {
        return permissionRepository.findByParentId(null);
    }

    @Override
    public Permission findRoot(Long id) {
        return permissionRepository.findOne(id);
    }

    @Override
    public List<Permission> findByParent(Long parentId, boolean include) {
        if (!include) {
            return permissionRepository.findByParentId(parentId);
        } else {
            return permissionRepository.findByIdOrParentId(parentId, parentId);
        }
    }

    @Override
    public List<Permission> findByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            Role role = user.getRole();
            if (role != null) {
                return permissionRepository.findByRole(role);
            }
        }
        return Collections.emptyList();
    }

}
